//
//  EpointMailDetailViewController.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-2-7.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointMailDetailViewController.h"
#import "MailInfo.h"
#import "NSString+Addtions.h"
#import "UIView+Addtions.h"
#import "EpointMailListViewController.h"
#import "UIPopoverListView.h"
#import "EpointMailSendViewController.h"
#import "EpointMailAtachViewController.h"
#import "Mail_GetDetail_Task.h"
#import "Mail_Delete_Task.h"
#import "Mail_SignMail_Task.h"
#import "Mail_GetFeedBackList_Task.h"
#import "Mail_AddFeedBack_Task.h"
#import "FeedBackInfo.h"
#import "SingleFile.h"
#import "SGActionView.h"
#import "EpointAttachDownloadListViewController.h"
#import "PGSegmentCtrl.h"
#import "PGTabBar.h"
#import "EpointPersonChooseViewController.h"
#import "EpointInputViewController.h"


#define SendPopListTAG 1002
#define MorePopListTAG 1003

#define AttachItemTAG 101
#define SendItemTAG 102
#define DeleteItemTAG 103
#define MoreItemTAG 104

#define PopoverListCellHeight 50.0f
#define MailDetailTaskId 1
#define MailDeleteTaskId 2
#define MailSignMailTaskId 3
#define MailGetFeedBackListTaskId 4
#define MailAddFeedBackTaskId 5
#define MailConvertTaskTaskId 6
#define MailTaskEndTaskId 7
#define MailAddSJRTaskId 8
#define FrameFeedBackTaskId 9

#define FontSize 15.0

@interface EpointMailDetailViewController () <UIWebViewDelegate, UIPopoverListViewDataSource, UIPopoverListViewDelegate, UITabBarDelegate, PGSegmentCtrlDelegate, PGTabBarDelegate> {
    MailInfo *mailInfo, *mailDetail;
    NSString *NeedTaskMonitor;
    NSString *mailType;// 0:收件箱 1:发件箱 2:任务邮件
    int selectedRow;
    
    NSArray *sendArray;
    NSArray *moreArray;
    
    UITabBarItem *attachItem;
    PGBarItem *mailAttachItem;
    UIPopoverListView *feedBackView;
    
}

@property (nonatomic, strong) UILabel *mailTitle;
@property (nonatomic, strong) UILabel *shortFromPerson;
@property (nonatomic, strong) UIButton *showOrHideDetail;
@property (nonatomic, strong) UIView *detailView;
@property (nonatomic, strong) UIWebView *mailContent;
@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) UIImageView *separatorLine;
@property (nonatomic, strong) UISegmentedControl *prevNext;
@property (nonatomic, strong) PGSegmentCtrl *segmentCtrl;

@end

@implementation EpointMailDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"邮件详情";
    
    mailInfo = [initParam objectForKey:@"MailInfo"];
    mailInfo.isRead=@"1";
    selectedRow = [[initParam objectForKey:@"selectedRow"] intValue];
    mailType = [initParam objectForKey:@"mailType"];
    
    //[self addRightNavigationButtons];
    [self addSegmentCtrl];
    
    //[self addBottomTabBar];
    [self addPGTabBar];
    
    [self addMailSubviews];
    
    [self getData];
}

- (void)addRightNavigationButtons {
    self.prevNext = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, 0, 60, 32)];
    if (ISIOS7) {
        [_prevNext insertSegmentWithImage:[UIImage imageNamed:@"btn_nav_prev"] atIndex:0 animated:YES];
        [_prevNext insertSegmentWithImage:[UIImage imageNamed:@"btn_nav_next"] atIndex:1 animated:YES];
    } else {
        [_prevNext insertSegmentWithImage:[UIImage imageNamed:@"btn_nav_prev_w"] atIndex:0 animated:YES];
        [_prevNext insertSegmentWithImage:[UIImage imageNamed:@"btn_nav_next_w"] atIndex:1 animated:YES];
    }
    
    _prevNext.momentary = YES;
    _prevNext.segmentedControlStyle = UISegmentedControlStyleBar;
    _prevNext.tintColor = self.navigationController.navigationBar.tintColor;
    [_prevNext addTarget:self action:@selector(handleActionBarPreviousNext:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *prevNextWrapper = [[UIBarButtonItem alloc] initWithCustomView:_prevNext];
    self.navigationItem.rightBarButtonItem = prevNextWrapper;
    
    [self updatePrevNextStatus];
}

- (void)addSegmentCtrl {
    self.segmentCtrl = [[PGSegmentCtrl alloc] initWithFrame:CGRectMake(0, 0, 80, 26)];
    _segmentCtrl.delegate = self;
    UIBarButtonItem *prevNextWrapper = [[UIBarButtonItem alloc] initWithCustomView:_segmentCtrl];
    self.navigationItem.rightBarButtonItem = prevNextWrapper;
    [self updatePrevNextStatus];
}

#pragma mark - PGSegmentCtrlDelegate

- (void)segmentCtrlDidSelected:(PGSegmentCtrl *)segmentCtrl {
    [self hideMBPHUD];
    [_contentView setContentOffset:CGPointMake(0, 0)];
    if (segmentCtrl.selectedSegmentIndex == 0) {
        selectedRow--;
    } else {
        selectedRow++;
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(changeSelectedRow:)]) {
        [_delegate changeSelectedRow:selectedRow];
    }
    
    [self updatePrevNextStatus];
    mailInfo = [_parentCtrl.dataArray objectAtIndex:selectedRow];
    
    _showOrHideDetail.selected = NO;
    _shortFromPerson.hidden = NO;
    _detailView.hidden = YES;
    
    [self updateTopSubView];
    
    [self getData];
}


- (void)updatePrevNextStatus {
    if (selectedRow == 0) {
        [self updatePrevStatus:NO nextStatus:YES];
        if (_parentCtrl.dataArray.count == 1) {
            [self updatePrevStatus:NO nextStatus:NO];
        }
    } else if (selectedRow == _parentCtrl.dataArray.count-1){
        [self updatePrevStatus:YES nextStatus:NO];
    } else {
        [self updatePrevStatus:YES nextStatus:YES];
    }
}

- (void)updatePrevStatus:(BOOL)prexEnable nextStatus:(BOOL)nextEnable {
    //    [_prevNext setEnabled:prexEnable forSegmentAtIndex:0];
    //    [_prevNext setEnabled:nextEnable forSegmentAtIndex:1];
    [_segmentCtrl setEnabled:prexEnable forSegmentAtIndex:0];
    [_segmentCtrl setEnabled:nextEnable forSegmentAtIndex:1];
}

- (void)handleActionBarPreviousNext:(UISegmentedControl *)segCtrl {
    
    [self hideMBPHUD];
    [_contentView setContentOffset:CGPointMake(0, 0)];
    if (segCtrl.selectedSegmentIndex == 0) {
        selectedRow--;
    } else {
        selectedRow++;
    }
    
    if (_delegate && [_delegate respondsToSelector:@selector(changeSelectedRow:)]) {
        [_delegate changeSelectedRow:selectedRow];
    }
    
    [self updatePrevNextStatus];
    mailInfo = [_parentCtrl.dataArray objectAtIndex:selectedRow];
    
    _showOrHideDetail.selected = NO;
    _shortFromPerson.hidden = NO;
    _detailView.hidden = YES;
    
    [self updateTopSubView];
    
    [self getData];
}

- (void)addBottomTabBar {
    
    UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, AppHeight-SystemTakeHeight-BottomBarHeight, AppWidth, BottomBarHeight)];
    tabBar.delegate = self;
    
    attachItem = [[UITabBarItem alloc] initWithTitle:@"附件" image:[UIImage imageNamed:@"img_attach3"] tag:AttachItemTAG];
    //    attachItem.tag = AttachItemTAG;
    
    UITabBarItem *sendItem = [[UITabBarItem alloc] initWithTitle:@"操作" image:[UIImage imageNamed:@"img_send"] tag:SendItemTAG];
    
    UITabBarItem *deleteItem = [[UITabBarItem alloc] initWithTitle:@"删除" image:[UIImage imageNamed:@"img_delete"] tag:DeleteItemTAG];
    
    UITabBarItem *moreItem = [[UITabBarItem alloc] initWithTitle:@"更多" image:[UIImage imageNamed:@"img_more"] tag:MoreItemTAG];
    
    NSArray *items = @[attachItem, sendItem, deleteItem, moreItem];
    [tabBar setItems:items];
    [self.view addSubview:tabBar];
}

- (void)addPGTabBar {
    PGTabBar *tabBar = [[PGTabBar alloc] initWithFrame:CGRectMake(0, AppHeight-SystemTakeHeight-BottomBarHeight, AppWidth, BottomBarHeight)];
    tabBar.delegate = self;
    mailAttachItem = [[PGBarItem alloc] initWithTitle:@"附件" image:[UIImage imageNamed:@"mail_attach"] tag:0];
    PGBarItem *operationItem = [[PGBarItem alloc] initWithTitle:@"操作" image:[UIImage imageNamed:@"operationMail"] tag:1];
    NSArray *items = @[mailAttachItem, operationItem];
    [tabBar setBarItems:items];
    [self.view addSubview:tabBar];
}

-(void)attachBtnPressed {
    
    NSMutableArray *fileList = [[NSMutableArray alloc]init];
    
    for (SingleFile *m in mailDetail.attachList) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:m.ATTACHFILENAME forKey:@"FileName"];
        [dic setObject:m.AttachGuid forKey:@"FolderGuid"];
        m.DownLoadUrl = [EpointBizTools getRealDownloadUrl:m.DownLoadUrl];
        [dic setObject:m.DownLoadUrl forKey:@"FileUrl"];
        [dic setObject:m.isBigFile forKey:@"isBigFile"];
        [fileList addObject:dic];
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:fileList forKey:@"FileList"];
    [params setObject:mailInfo.MAILGUID forKey:@"FolderGuid"];
    EpointAttachDownloadListViewController *v = [[EpointAttachDownloadListViewController alloc]init];
    v.passParam = params;
    [self.navigationController pushViewController:v animated:YES];
}

- (void)deleteBtnPressed {
    NSLog(@"deleteBtnPressed ...");
    // TODO: delete
    [SGActionView showAlertWithTitle:AreYouSureToDeleteThisMaill message:nil leftButtonTitle:@"取消" rightButtonTitle:@"确定" selectedHandle:^(NSInteger index) {
        if (index == 1) {
            [self showMBPHUD];
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:mailInfo.MAILGUID forKey:@"MailGuidList"];
            [self startTask:@"Mail_Delete_Task" withParams:params withTaskId:MailDeleteTaskId];
        }
    }];
    //    [self deleteSuccess];
}

- (void)deleteSuccess {
    if (_delegate && [_delegate respondsToSelector:@selector(mailDetailDeleteCurrentOne)]) {
        [_delegate mailDetailDeleteCurrentOne];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)sendBtnPressed {
    NSLog(@"sendBtnPressed ...");
    NSString *mailState=@"转任务邮件";
    if ([@"1" isEqualToString:NeedTaskMonitor]) {
        mailState=@"结束任务邮件";
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *oaVersion =[userDefaults objectForKey:Epoint_OAVesion];
    if ([oaVersion isEqualToString:@"8.0"]) {
        if ([mailType isEqualToString:@"1"]) {
            //发件箱
            sendArray = @[ @"转发",@"反馈",@"添加收件人",mailState];
            if([@"2" isEqualToString:NeedTaskMonitor]){
                sendArray = @[ @"转发",@"反馈",@"添加收件人"];
            }
        }else if([mailType isEqualToString:@"0"]||[mailType isEqualToString:@"2"]){
            //收件箱
            sendArray = @[@"回复", @"转发",@"反馈",@"添加收件人",mailState];
            if([@"2" isEqualToString:NeedTaskMonitor]){
                sendArray = @[@"回复", @"转发",@"反馈",@"添加收件人"];
            }
        }
    }else{
        //#################oa 7.0####################
        if ([mailType isEqualToString:@"1"]) {
            //发件箱
            sendArray = @[ @"转发",mailState];
            if([@"2" isEqualToString:NeedTaskMonitor]){
                sendArray = @[ @"转发"];
            }
        }else if([mailType isEqualToString:@"0"]||[mailType isEqualToString:@"2"]){
            //收件箱
            sendArray = @[@"回复", @"转发",mailState];
            if([@"2" isEqualToString:NeedTaskMonitor]){
                sendArray = @[@"回复", @"转发"];
            }
        }
    }
    
    
    [self showPopoverListView:SendPopListTAG];
}

- (void)moreBtnPressed {
    NSLog(@"moreBtnPressed ...");
    if (moreArray == nil) {
        moreArray = @[@"添加邮件反馈", @"更多2", @"更多3"];
    }
    [self showPopoverListView:MorePopListTAG];
}

- (void)showPopoverListView:(int)tag {
    CGFloat pWidth = AppWidth - 60;
    
    int rowCount = 0;
    NSString *title = @"";
    
    switch (tag) {
        case SendPopListTAG: {
            rowCount = sendArray.count;
            title = @"发送操作";
        }
            break;
        case MorePopListTAG: {
            rowCount = moreArray.count;
            title = @"更多";
        }
            break;
        default:
            break;
    }
    
    CGFloat pHeight = TitleHeight + PopoverListCellHeight*rowCount;
    CGFloat pTop = (AppHeight - SystemTakeHeight - BottomBarHeight - pHeight)*0.5;
    
    UIPopoverListView *poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(30, pTop, pWidth, pHeight)];
    poplistview.delegate = self;
    poplistview.datasource = self;
    poplistview.listView.scrollEnabled = TRUE;
    poplistview.parentView = self.view;
    poplistview.tag = tag;
    [poplistview setTitle:title];
    [poplistview show];
}

- (void)addMailSubviews {
    
    self.contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, AppWidth, AppHeight- SystemTakeHeight - BottomBarHeight)];
    _contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_contentView];
    
    // title
    self.mailTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    _mailTitle.numberOfLines = 0;
    _mailTitle.font = [UIFont systemFontOfSize:FontSize];
    _mailTitle.left = 10;
    _mailTitle.top = 5;
    _mailTitle.width = AppWidth - 20;
    [self.contentView addSubview:_mailTitle];
    
    
    self.shortFromPerson = [[UILabel alloc] initWithFrame:CGRectZero];
    _shortFromPerson.font = [UIFont boldSystemFontOfSize:FontSize];
    _shortFromPerson.textColor = COLOR(95, 162, 7);
    _shortFromPerson.left = 10;
    [self.contentView addSubview:_shortFromPerson];
    
    
    self.detailView = [[UIView alloc] initWithFrame:CGRectZero];
    _detailView.left = 10;
    _detailView.hidden = YES;
    [self.contentView addSubview:_detailView];
    
    
    self.showOrHideDetail = [UIButton buttonWithType:UIButtonTypeCustom];
    [_showOrHideDetail setBackgroundImage:[UIImage imageNamed:@"showOrHide"] forState:UIControlStateNormal];
    [_showOrHideDetail setTitle:@"显示详情" forState:UIControlStateNormal];
    [_showOrHideDetail setTitle:@"隐藏详情" forState:UIControlStateSelected];
    [_showOrHideDetail.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [_showOrHideDetail setTitleColor:COLOR(30, 144, 255) forState:UIControlStateNormal];
    [_showOrHideDetail setTitleColor:COLOR(30, 144, 255) forState:UIControlStateHighlighted];
    [_showOrHideDetail addTarget:self action:@selector(showOrHidePressed:) forControlEvents:UIControlEventTouchUpInside];
    _showOrHideDetail.width = 63;
    _showOrHideDetail.height = 24;
    _showOrHideDetail.left = AppWidth - _showOrHideDetail.width - 10;
    _shortFromPerson.width = _showOrHideDetail.left - 15;
    [self.contentView addSubview:_showOrHideDetail];
    
    self.separatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, _shortFromPerson.bottom+5, AppWidth, 1)];
    _separatorLine.alpha = 0.5;
    _separatorLine.backgroundColor = [UIColor grayColor];
    [self.contentView addSubview:_separatorLine];
    
    
    self.mailContent = [[UIWebView alloc] initWithFrame:CGRectZero];
    _mailContent.delegate = self;
    _mailContent.left = 0;
    _mailContent.width = AppWidth;
    _mailContent.scrollView.bounces = NO;
    [self.contentView addSubview:_mailContent];
    
    [self updateTopSubView];
}

- (void)updateTopSubView {
    _mailTitle.text = mailInfo.Subject;
    CGFloat singleHeight = [NSString getMailDetailSingleLineHeight];
    CGFloat titleHeight = [mailInfo.Subject getMailDetailTitleHeight];
    titleHeight = (titleHeight>singleHeight) ? (singleHeight*2+15) : (singleHeight+5);
    _mailTitle.height = titleHeight;
    
    
    _shortFromPerson.text = mailInfo.FROMDISPNAME;
    [_shortFromPerson sizeToFit];
    _shortFromPerson.top = _mailTitle.bottom;
    
    
    _showOrHideDetail.centerY = _shortFromPerson.centerY;
    
    
    _detailView.top = _mailTitle.bottom;
    
    _separatorLine.top = _shortFromPerson.bottom+5;
    
    _mailContent.top = _separatorLine.bottom;
}

- (void)showOrHidePressed:(UIButton *)button {
    _showOrHideDetail.selected = !_showOrHideDetail.selected;
    _shortFromPerson.hidden = _showOrHideDetail.selected;
    _detailView.hidden = !_showOrHideDetail.selected;
    
    if (_showOrHideDetail.selected) {
        _separatorLine.top = _detailView.bottom;
    } else {
        _separatorLine.top = _shortFromPerson.bottom + 5;
    }
    
    _mailContent.top = _separatorLine.bottom ;
    [_contentView setContentSize:CGSizeMake(AppWidth, _mailContent.bottom)];
}

#pragma mark - getData

- (void)getData {
    [self showMBPHUD];
    // !!!!: here response test data
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
    [self startTask:@"Mail_GetDetail_Task" withParams:params withTaskId:MailDetailTaskId];
}

- (void)updateDetailView {
    //!!!!: Detail subView
    for (UIView *subView in _detailView.subviews) {
        [subView removeFromSuperview];
    }
    
    UIFont *font = [UIFont systemFontOfSize:FontSize];
    UIColor *titleColor = [UIColor grayColor];
    
    // from
    UILabel *fromTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    fromTitle.text = @"发件人:";
    fromTitle.font = font;
    fromTitle.textColor = titleColor;
    [fromTitle sizeToFit];
    [_detailView addSubview:fromTitle];
    
    UILabel *fromValue = [[UILabel alloc] initWithFrame:CGRectZero];
    fromValue.text = mailInfo.FROMDISPNAME;
    fromValue.textColor = titleColor;
    fromValue.font = font;
    [fromValue sizeToFit];
    fromValue.width = _showOrHideDetail.left - 20 - fromTitle.width;
    fromValue.left = fromTitle.right + 5;
    [_detailView addSubview:fromValue];
    
    
    // to
    UILabel *toTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    toTitle.text = @"收件人:";
    toTitle.font = font;
    toTitle.textColor = titleColor;
    [toTitle sizeToFit];
    toTitle.top = fromTitle.bottom+5;
    [_detailView addSubview:toTitle];
    
    UILabel *toValue = [[UILabel alloc] initWithFrame:CGRectZero];
    NSString *toValueText = mailInfo.ToUserDispNameList;
    if ([mailInfo.ToUserDispNameList hasSuffix:@";"]) {
        toValueText = [mailInfo.ToUserDispNameList substringToIndex:toValueText.length-1];
    }
    toValue.text = toValueText;
    toValue.textColor = titleColor;
    toValue.font = font;
    [toValue sizeToFit];
    toValue.numberOfLines = 0;
    toValue.width = AppWidth - 20 - toTitle.width;
    CGFloat toValueHeight = [toValue.text getTextHeightWithFont:font withSuperViewWidth:toValue.width];
    toValue.height = toValueHeight;
    toValue.top = toTitle.top;
    toValue.left = toTitle.right + 5;
    [_detailView addSubview:toValue];
    
    // cs
    UILabel *csTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    csTitle.text = @"抄送人:";
    csTitle.font = font;
    csTitle.textColor = titleColor;
    [csTitle sizeToFit];
    csTitle.top = toTitle.bottom+5+toValueHeight-20;
    [_detailView addSubview:csTitle];
    
    UILabel *csValue = [[UILabel alloc] initWithFrame:CGRectZero];
    NSString *csValueText = mailInfo.ChaoSongUserDispNameList;
    if ([mailInfo.ChaoSongUserDispNameList hasSuffix:@";"]) {
        csValueText = [mailInfo.ChaoSongUserDispNameList substringToIndex:csValueText.length-1];
    }
    if (!IsiOS7Over) {
        csValueText=[csValueText isEqualToString:@""]?@" ":csValueText;
    }
    csValue.text = csValueText;
    csValue.textColor = titleColor;
    csValue.font = font;
    [csValue sizeToFit];
    csValue.numberOfLines = 0;
    csValue.width = AppWidth - 20 - csTitle.width;
    CGFloat csValueHeight = [csValue.text getTextHeightWithFont:font withSuperViewWidth:csValue.width];
    csValue.height = csValueHeight;
    csValue.top = csTitle.top;
    csValue.left = csTitle.right + 5;
    [_detailView addSubview:csValue];
    
    // date
    UILabel *dateTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    dateTitle.text = @"时";
    dateTitle.font = font;
    dateTitle.textColor = titleColor;
    [dateTitle sizeToFit];
    dateTitle.top = csValue.bottom+6;
    [_detailView addSubview:dateTitle];
    
    UILabel *dateTitle2 = [[UILabel alloc] initWithFrame:CGRectZero];
    dateTitle2.text = @"间:";
    dateTitle2.font = font;
    dateTitle2.textColor = titleColor;
    [dateTitle2 sizeToFit];
    dateTitle2.top = csValue.bottom+6;
    dateTitle2.left = dateTitle.right+15;
    [_detailView addSubview:dateTitle2];
    
    
    UILabel *dateValue = [[UILabel alloc] initWithFrame:CGRectZero];
    dateValue.text = [EpointDateUtils convertToMailListNeededFormat2:mailInfo.SENDTIME];
    dateValue.textColor = titleColor;
    dateValue.font = font;
    [dateValue sizeToFit];
    dateValue.left = dateTitle2.right + 5;
    dateValue.top = dateTitle.top;
    [_detailView addSubview:dateValue];
    
    _detailView.height = dateValue.bottom + 5;
    //    _detailView.width = AppWidth - 20;
//    _detailView.backgroundColor = [UIColor redColor];
    int attachCount = mailDetail.attachList.count;
    NSString *badgeNum = attachCount==0 ? nil : [NSString stringWithFormat:@"%d", attachCount];
    //    [attachItem setBadgeValue:badgeNum];
    [mailAttachItem setBadgeValue:badgeNum];
}

- (void)updateContentView {
    
    [self showMBPHUD];
    NSString *mailContent = mailDetail.MailContent;
    if (mailDetail == nil || [mailContent isEqualToString:@""]) {
        mailContent = @"(无内容)";
    }
    
    [_mailContent loadHTMLString:[NSString stringWithFormat:@"<div id='foo'>%@</div>", mailContent] baseURL:nil];
}


#pragma mark - UIWebViewDelegate

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self hideMBPHUD];
    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"foo\").offsetHeight;"] floatValue];
    NSLog(@"height:%f", height);
    CGRect frame = webView.frame;
    webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height+25);//25
    NSArray *arr = [webView subviews];
    UIScrollView *scrollView = [arr objectAtIndex:0];
    if (scrollView.contentSize.height != 0) {
        webView.height = scrollView.contentSize.height;
    }
    [_contentView setContentSize:CGSizeMake(AppWidth, webView.bottom)];
}

#pragma mark - UIPopoverListViewDataSource

- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView
                    cellForIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                   reuseIdentifier:identifier];
    NSString *lbText;
    switch (popoverListView.tag) {
        case SendPopListTAG:
            lbText = [sendArray objectAtIndex:indexPath.row];
            break;
        case MorePopListTAG:
            lbText = [moreArray objectAtIndex:indexPath.row];
            break;
        default:
            break;
    }
    cell.textLabel.font = [UIFont systemFontOfSize:18.0];
    cell.textLabel.text = lbText;
    return cell;
}

- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section {
    
    int numberOfRow = 0;
    switch (popoverListView.tag) {
        case SendPopListTAG:
            numberOfRow = sendArray.count;
            break;
        case MorePopListTAG:
            numberOfRow = moreArray.count;
            break;
        default:
            break;
    }
    return numberOfRow;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s : %d", __func__, indexPath.row);
    switch (popoverListView.tag) {
        case SendPopListTAG:
            [self replyOrForwardMail:indexPath.row];
            break;
        case MorePopListTAG:
            //numberOfRow = moreArray.count;
            [self moreCustomItemClicked:indexPath.row];
            break;
        default:
            break;
    }
}

- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return PopoverListCellHeight;
}

- (void)dismissFromParentView:(UIPopoverListView *)popoverListView {
    
}

- (void)addFeedBackContent:(NSString *)content {
    NSLog(@"content:%@", content);
    if (![EpointStringUtil stringIsNotNull:content]) {
        [self toastMessage:@"反馈内容不能为空！"];
        return;
    }
    
    NSString *tempStr = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (![EpointStringUtil stringIsNotNull:tempStr]) {
        [self toastMessage:@"请输入有效内容！"];
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
    [params setObject:content forKey:@"FeedBackContent"];
    [self startTask:@"Mail_AddFeedBack_Task" withParams:params withTaskId:MailAddFeedBackTaskId];
}

#pragma mark - Some Actions

- (void)replyOrForwardMail:(int)index {
    
    NSMutableDictionary *params = initParam;
    [params setObject:mailDetail forKey:@"MailInfo"];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *oaVersion =[userDefaults objectForKey:Epoint_OAVesion];
    
    if ([oaVersion isEqualToString:@"8.0"]) {
        if ([mailType isEqualToString:@"0"]||[mailType isEqualToString:@"2"]) {
            //收件箱
            if (index==0) {
                [params setObject:@"Reply" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            } else if(index==1) {
                [params setObject:@"Forwad" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            }else if(index==2){
                [self showFeedBackView];
            }else if(index==3){
                //添加收件人
                [self addSJR];
            }else if(index==4){
#pragma mark 转任务邮件
                [self showMBPHUD];
                if ([NeedTaskMonitor isEqualToString:@"0"]) {
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_ConvertTask_Task" withParams:params withTaskId:MailConvertTaskTaskId];
                }else if([NeedTaskMonitor isEqualToString:@"1"]){
#pragma mark 结束任务邮件
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_TaskEnd_Task" withParams:params withTaskId:MailTaskEndTaskId];
                }
            }
        }else if([mailType isEqualToString:@"1"]){
            if(index==0) {
                [params setObject:@"Forwad" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            }else if(index==1){
                [self showFeedBackView];
            }else if(index==2){
                //添加收件人
                [self addSJR];
            }else if(index==3){
#pragma mark 转任务邮件
                [self showMBPHUD];
                if ([NeedTaskMonitor isEqualToString:@"0"]) {
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_ConvertTask_Task" withParams:params withTaskId:MailConvertTaskTaskId];
                }else if([NeedTaskMonitor isEqualToString:@"1"]){
#pragma mark 结束任务邮件
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_TaskEnd_Task" withParams:params withTaskId:MailTaskEndTaskId];
                }
            }
            
        }
    }else{
        //###################oa 7.0##################
        if ([mailType isEqualToString:@"0"]||[mailType isEqualToString:@"2"]) {
            //收件箱
            if (index==0) {
                [params setObject:@"Reply" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            } else if(index==1) {
                [params setObject:@"Forwad" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            }else if(index==2){
#pragma mark 转任务邮件
                [self showMBPHUD];
                if ([NeedTaskMonitor isEqualToString:@"0"]) {
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_ConvertTask_Task" withParams:params withTaskId:MailConvertTaskTaskId];
                }else if([NeedTaskMonitor isEqualToString:@"1"]){
#pragma mark 结束任务邮件
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_TaskEnd_Task" withParams:params withTaskId:MailTaskEndTaskId];
                }
            }
        }else if([mailType isEqualToString:@"1"]){
            if(index==0) {
                [params setObject:@"Forwad" forKey:@"SendType"];
                EpointMailSendViewController *sendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
                [self.navigationController pushViewController:sendCtrl animated:YES];
            }else if(index==1){
#pragma mark 转任务邮件
                [self showMBPHUD];
                if ([NeedTaskMonitor isEqualToString:@"0"]) {
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_ConvertTask_Task" withParams:params withTaskId:MailConvertTaskTaskId];
                }else if([NeedTaskMonitor isEqualToString:@"1"]){
#pragma mark 结束任务邮件
                    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
                    [self startTask:@"Mail_TaskEnd_Task" withParams:params withTaskId:MailTaskEndTaskId];
                }
            }
            
        }

    }
    
}

-(void)addSJR{
    [EpointPersonChooseViewController pushChoosePerson:self WithTag:@"sjr" AndNames:@"" AndGuids:@""];
}
#pragma mark - people choose call back

-(void)epointPerson:(NSString *)controlTag chooseData:(NSMutableArray *)data
{
    NSArray *arr =[EpointPersonChooseViewController getChoosedArray:data];
    if ([controlTag isEqualToString:@"sjr"]) {
        NSString *tempStr = [arr objectAtIndex:0];
        NSString* sjrGuids = [arr objectAtIndex:1];
        if (sjrGuids!=nil&&![@"" isEqualToString:sjrGuids]) {
            [self showMBPHUD];
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
            [params setObject:sjrGuids forKey:@"userList"];
            [self startTask:@"Mail_AddReceiver_Task" withParams:params withTaskId:MailAddSJRTaskId];
        }
        
    }
}

- (void)moreCustomItemClicked:(int)index {
    switch (index) {
        case 0:
            [self showFeedBackView];
            break;
        case 1:
            break;
        default:
            break;
    }
}

- (void)showFeedBackView {
    
    [EpointInputViewController involeInputViewController:self vctitle:@"邮件反馈" preContent:@"" handler:^(NSString *text){
        NSLog(@"%@",text);
        [self addFeedBackContent:text];
    }];
}

#pragma mark - UITabBarDelegate

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    switch (item.tag) {
        case AttachItemTAG:
            [self attachBtnPressed];
            break;
        case SendItemTAG:
            [self sendBtnPressed];
            break;
        case DeleteItemTAG:
            [self deleteBtnPressed];
            break;
        case MoreItemTAG:
            [self moreBtnPressed];
            break;
        default:
            break;
    }
}


#pragma mark-  PGTabBarDelegate

- (void)pgTabBar:(PGTabBar *)tabBar didClickedAtIndex:(NSInteger)index {
    
    if (index == 0) {
        [self attachBtnPressed];
    } else {
        [self sendBtnPressed];
    }
}

#pragma mark -

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj {
    
    [self hideMBPHUD];
    
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (![[arr objectAtIndex:0]isEqualToString:@"1"]) {
        
        if (taskId != MailGetFeedBackListTaskId) {
            [self toastMessage:[arr objectAtIndex:1]];
        }
        if (taskId == MailDetailTaskId) {
            mailDetail = nil;
            [self updateData];
        }
        return;
    }
    
    if (taskId == MailDetailTaskId) {
        NSMutableArray* array = [arr lastObject];
        mailDetail = [array lastObject];
        mailInfo=mailDetail;
        NeedTaskMonitor = mailDetail.NeedTaskMonitor;
        [self updateData];
        [self getFeedbackInfo];
    } else if (taskId == MailDeleteTaskId) {
        [self toastMessage:[arr lastObject]];
        [self deleteSuccess];
    } else if (taskId == MailGetFeedBackListTaskId) {
        NSArray *feedArr = [arr lastObject];
        [self updateMailContent:feedArr];
    } else if (taskId == MailAddFeedBackTaskId) {
        [self toastMessage:[arr objectAtIndex:1]];
        [feedBackView dismiss];
        [self getFeedbackInfo];
    } else if(taskId==MailConvertTaskTaskId){
        NeedTaskMonitor=@"1";
        NSString *showStr = [arr lastObject];
        [self toastMessage:showStr];
        [self getFeedbackInfo];
    } else if(taskId==MailTaskEndTaskId){
        NeedTaskMonitor=@"2";
        NSString *showStr = [arr lastObject];
        [self toastMessage:showStr];
        [self getFeedbackInfo];
    }else if(taskId==MailAddSJRTaskId){
        //添加收件人成功，无处理
        [self getData];
    }
}

- (void)updateMailContent:(NSArray *)feedArr {
    NSString *feedBackHtml = [self createHTMLTableWithArray:feedArr];
    NSString *mailContent = mailDetail.MailContent;
    if (mailDetail == nil || [mailContent isEqualToString:@""]) {
        mailContent = @"(无内容)";
    }
    //NSString *disContent = [NSString stringWithFormat:@"%@%@",HTMLSTYPE1,mailContent];
    //    disContent = [EpointStringUtil filterXmlString:<#(NSString *)#>:disContent];
    NSString *finalContent = [NSString stringWithFormat:@"%@<br/><br/>%@",mailContent,feedBackHtml];
    [_mailContent loadHTMLString:[NSString stringWithFormat:@"<div id='foo'>%@</div>", finalContent] baseURL:nil];
}

- (NSString *)createHTMLTableWithArray:(NSArray *)array {
    NSLog(@"反馈数量：%i",array.count);
    NSMutableString *feedHTML = [[NSMutableString alloc]initWithString:@""];
    if (array.count>0) {
        [feedHTML appendString:@"<TABLE style=\"BORDER-LEFT-WIDTH: 0px; BORDER-COLLAPSE: collapse; BORDER-RIGHT-WIDTH: 0px;\" cellSpacing=0 cellPadding=0 align=center border=0 width='100%'>"];
        [feedHTML appendString:@"<tr>"];
        [feedHTML appendString:@"<TD style=\"BORDER-RIGHT: medium none; BORDER-LEFT: medium none; BORDER-BOTTOM: medium none;background-color: #33A1C9;text-align: center;\" height=40>"];
        [feedHTML appendString:[NSString stringWithFormat:@"<font color=white><strong>邮 件 反 馈</strong></font>"]];
        [feedHTML appendString:@"</td>"];
        [feedHTML appendString:@"</tr>"];
        for (int i=0; i<array.count; i++) {
            FeedBackInfo *m = [array objectAtIndex:i];
            if (i%2 !=0) {
                [feedHTML appendString:@"<tr>"];
                [feedHTML appendString:@"<TD style=\"BORDER-RIGHT: medium none; BORDER-LEFT: medium none; BORDER-BOTTOM: medium none;background-color: #DCDCDC;\" height=40>"];
                [feedHTML appendString:[NSString stringWithFormat:@"<font color='#3D59AB'>%@&nbsp;&nbsp;%@</font>",m.DISPNAME,m.BackTime]];
                [feedHTML appendString:@"</td>"];
                [feedHTML appendString:@"</tr>"];
                [feedHTML appendString:@"<tr>"];
                [feedHTML appendString:@"<td style=\"BORDER-RIGHT: medium none; BORDER-LEFT: medium none; BORDER-TOP: medium none;background-color: #DCDCDC;\" height=40><font color='#0B1746'>"];
                [feedHTML appendString:m.Content];
                [feedHTML appendString:@"</font></td>"];
                [feedHTML appendString:@"</tr>"];
            }else{
                [feedHTML appendString:@"<tr>"];
                [feedHTML appendString:@"<TD style=\"BORDER-RIGHT: medium none; BORDER-LEFT: medium none; BORDER-BOTTOM: medium none;background-color: #FFFAF0;\" height=40>"];
                [feedHTML appendString:[NSString stringWithFormat:@"<font color='#5E2612'>%@&nbsp;&nbsp;%@</font>",m.DISPNAME,m.BackTime]];
                [feedHTML appendString:@"</td>"];
                [feedHTML appendString:@"</tr>"];
                [feedHTML appendString:@"<tr>"];
                [feedHTML appendString:@"<td style=\"BORDER-RIGHT: medium none; BORDER-LEFT: medium none; BORDER-TOP: medium none;background-color: #FFFAF0;\" height=40><font color='#734A12'>"];
                [feedHTML appendString:m.Content];
                [feedHTML appendString:@"</font></td>"];
                [feedHTML appendString:@"</tr>"];
            }
            
        }
        [feedHTML appendString:@"</table>"];
    }
    return feedHTML;
}

- (void)updateData {
    if (!mailType) {
        [self markLocalMailStatus];
    }
    
    [self updateDetailView];
    [self updateContentView];
}

- (void)signMailAsRead {
    // 打开邮件后，接口便标记为已读
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mailInfo.MAILGUID forKey:@"MailGuidList"];
    [self startTask:@"Mail_SignMail_Task" withParams:params withTaskId:MailSignMailTaskId];
}

- (void)markLocalMailStatus {
    if (_delegate && [_delegate respondsToSelector:@selector(mailDetailCtrlIsLoadFinished:)]) {
        [_delegate mailDetailCtrlIsLoadFinished:self];
    }
}

- (void)getFeedbackInfo {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mailInfo.MAILGUID forKey:@"MailGuid"];
    [self startTask:@"Mail_GetFeedBackList_Task" withParams:params withTaskId:MailGetFeedBackListTaskId];
}

#pragma mark - test data

- (void)addTestData {
    [self hideMBPHUD];
    [self updateData];
}

- (NSArray *)getSomeAttachData {
    
    NSDictionary *dic0 = @{@"filename": @"发文原稿.doc",
                           @"fileurl": @"",
                           @"folderguid": @""};
    NSDictionary *dic1 = @{@"filename": @"发文原稿.jpg",
                           @"fileurl": @"",
                           @"folderguid": @""};
    NSDictionary *dic2 = @{@"filename": @"发文原稿.txt",
                           @"fileurl": @"",
                           @"folderguid": @""};
    NSDictionary *dic3 = @{@"filename": @"发文原稿.pdf",
                           @"fileurl": @"",
                           @"folderguid": @""};
    NSDictionary *dic4 = @{@"filename": @"发文原稿.ppt",
                           @"fileurl": @"",
                           @"folderguid": @""};
    NSArray *tempArr = @[dic0, dic1, dic2, dic3, dic4];
    return tempArr;
}

@end
